package cn.zhaopin.starter.security.point;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: 自定义http basic认证失败服务端点
 *
 * @author zuomin (myleszelic@outlook.com)
 * @date: 2021/09/28-15:46
 */
public class BasicHttpBasicServerAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        Map<String, Object> result = new HashMap<>(4);
        result.put("code", "40001");
        result.put("httpCode", HttpStatus.UNAUTHORIZED.value());
        result.put("message", "Unauthorized path: " + request.getPath().value());
        byte[] resultBytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer dataBuffer = response.bufferFactory().wrap(resultBytes);
        return response.writeWith(Mono.just(dataBuffer));
    }
}
